import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectClassDemo {
    public static void reflectNewInstance() throws ClassNotFoundException, InstantiationException, IllegalAccessException {

        Class<?> classStudent=Class.forName("Student");
        Object o = classStudent.newInstance();
        Student student=(Student) o;
        System.out.println("获取学生对象:"+student);
    }
    public static void reflectPrivateConstructor() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> classStudent=Class.forName("Student");
        Constructor<?> declaredConstructor = classStudent.getDeclaredConstructor(String.class, int.class);
        declaredConstructor.setAccessible(true);
        Student o = (Student) declaredConstructor.newInstance("颜颜", 19);
        System.out.println(o);
        System.out.println("获得私有构造函数且修改年龄和姓名");
    }
    //对私有属性，进行修改
    public static void reflectPrivateFiele() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class<?> classStudent=Class.forName("Student");
        Field name = classStudent.getDeclaredField("name");
        name.setAccessible(true);
        Student o = (Student) classStudent.newInstance();
//        System.out.println(o);
        name.set(o,"可可");
        String name1=(String) name.get(o);
        System.out.println(name1);
    }
    private static void reflectPrivateMethod() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class<?> classStudent=Class.forName("Student");
        Method function = classStudent.getDeclaredMethod("eat");
        System.out.println("私有方法的名称为:"+function.getName());
        function.setAccessible(true);
        Student o = (Student) classStudent.newInstance();
//        function.invoke(o,"我今天吃了干锅贴");
    }

    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, NoSuchFieldException {
//        reflectPrivateConstructor();
//        reflectPrivateFiele();
        reflectPrivateMethod();

    }

}
